package com.cbn.lib_screen.manager;

import android.util.Log;

import androidx.annotation.NonNull;

import com.cbn.lib_screen.entity.DeviceInfo;
import com.cbn.lib_screen.event.DeviceEvent;

import org.fourthline.cling.model.meta.Device;
import org.fourthline.cling.model.types.DeviceType;
import org.fourthline.cling.model.types.UDADeviceType;
import org.greenrobot.eventbus.EventBus;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @author lzan13
 * @date 2022/3/9
 * 设备管理器，保存当前包含设备列表，以及当前选中设备
 */
public enum  DeviceManager {
    INSTANCE;
    /**
     * DMR 设备 类型
     */
    private static final DeviceType DMR_DEVICE = new UDADeviceType("MediaRenderer");

    private List<Device> clingDeviceList;
    private DeviceInfo currClingDevice;

    /**
     * 私有构造方法
     */
     DeviceManager() {
        if (clingDeviceList == null) {
            clingDeviceList = new CopyOnWriteArrayList<>();
        }
        clingDeviceList.clear();
    }



    /**
     * 获取当前 Cling 设备
     */
    public DeviceInfo getCurrClingDevice() {
        return currClingDevice;
    }

    /**
     * 设置当前 Cling 设备
     */
    public void setCurrClingDevice(DeviceInfo currClingDevice) {
        this.currClingDevice = currClingDevice;
        Log.e("==>", "setCurrClingDevice");
    }

    /**
     * 添加设备到设备列表
     */
    public  void addDevice(@NonNull Device device) {
        if (device.getType().equals(DMR_DEVICE)) {
            if (!clingDeviceList.contains(device)) {
                clingDeviceList.add(device);
                EventBus.getDefault().post(new DeviceEvent());
            }
        }
    }

    /**
     * 从设备列表移除设备
     */
    public void removeDevice(@NonNull Device device) {
        Device clingDevice = getClingDevice(device);
        if (clingDevice != null) {
            clingDeviceList.remove(clingDevice);
        }
    }

    /**
     * 获取设备
     */
    public Device getClingDevice(@NonNull Device device) {
        for (Device tmpDevice : clingDeviceList) {
            if (device.equals(tmpDevice)) {
                return tmpDevice;
            }
        }
        return null;
    }

    /**
     * 获取设备列表
     */
    public List<Device> getClingDeviceList() {
        return clingDeviceList;
    }

    /**
     * 设置设备列表
     */
    public void setClingDeviceList(List<Device> list) {
        clingDeviceList = list;
    }


    /**
     * 销毁
     */
    public void destroy() {
        if (clingDeviceList != null) {
            clingDeviceList.clear();
        }
    }
}
